package com.tul.exercise.base.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description 《java编程思想》第22章 练习题7：
 *
 * 正则表达式
 **/
public class RegexTextArea extends JFrame{
    // 字符串输入框
    private TextField strField = new TextField();

    // 正则表达式输入框
    private TextField regexField = new TextField();

    private Button test = new Button("Test");

    private JTextArea out = new JTextArea(40, 20);

    public RegexTextArea() {
        setLayout(new FlowLayout());
        add(test);
        add(strField);
        add(regexField);

        add(out);

        test.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String str = strField.getText();
                String pettern = regexField.getText();

                if (str != null) {
                    Pattern p = Pattern.compile(pettern);
                    Matcher m = p.matcher(str);

                    if (m.find()) {
                        out.setText("");
                        out.setText(m.group());
                    }
                }
            }
        });

    }

    public static void main(String[] args) {
        SwingConsole.run(new RegexTextArea(), 500, 1000);
    }



}
